import os
import re

import cv2



def get_video_data(address: str,):
    # 打开视频文件
    cap = cv2.VideoCapture(address)
    # 获取视频的帧率、宽度和高度
    fps = round(cap.get(cv2.CAP_PROP_FPS))
    yuan_fps = cap.get(cv2.CAP_PROP_FPS)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    # 假设原视频一秒120帧
    print(f'原始帧率为{yuan_fps}')
    print(f'帧率、宽度和高度分别为：{fps}, {width}, {height}')
    # # 计算慢放后的帧率，并确保它是一个合理的数值
    slow_fps = max(1, int(fps / fps))  # 确保帧率至少为1，慢放fps倍,即无论原视频多少帧，都慢放到1帧1秒
    print(f'慢放后的帧率: {slow_fps}')
    mulu = os.path.dirname(address)
    # print(mulu)
    numbers = os.path.basename(address)
    slow_video = numbers.split('.',1)
    slow_video_name = os.path.join(mulu, slow_video[0] + '_' + 'slow.' + slow_video[1])
    # # print(slow_video_name)
    return cap, fps, width, height, slow_fps, slow_video_name


def create_slow_video(address_slow: str, cap, fps, width, height, slow_fps, ):
    # 创建VideoWriter对象，用于写入慢放后的视频
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    output_path = address_slow
    out = cv2.VideoWriter(output_path, fourcc, slow_fps, (width, height))

    if not cap.isOpened():
        print("无法打开视频文件")
    elif not out.isOpened():
        print("无法创建输出视频文件")

    while True:
        # 读取视频的每一帧
        ret, frame = cap.read()
        if not ret:
            print("未能获取到帧，终止中...")
            break
        # 将帧写入新的视频文件
        out.write(frame)
    # 释放资源
    cap.release()
    out.release()
    cv2.destroyAllWindows()
    print(f"视频已保存至: {output_path}")
    return output_path


if __name__ == '__main__':
    cap, fps, width, height, slow_fps, slow_video_name=get_video_data('/Users/zltest/Desktop/wireless_1080_vd.mp4')
    print(slow_video_name)
    # 单模块调试，第一个参数自己指定慢放视频名字
    # create_slow_video(slow_video_name, cap, fps, width, height, slow_fps)